<!-- route: // name: thecondAuth-->
<template>
  <div class="secondAuth">
    <el-form>
      <el-form-item :rules="[{required: true}]" class="secondAuthRadio" label="认证方式">
        <div class="btnList">
          <span :class="[{'btnListActive': activeIndex === 0}]" @click="activeIndex = 0"><b
            class="el-icon-postcard"></b>法人授权认证</span>
          <span :class="[{'btnListActive': activeIndex === 1}]" @click="activeIndex = 1"><b class="el-icon-user"></b>法人本人授权认证<span
            style="font-size: 12px;font-weight: 300">（仅支持大陆人士）</span></span>
<!--          <span :class="[{'btnListActive': activeIndex === 2}]" @click="activeIndex = 2"><b-->
<!--            class="el-icon-edit-outline"></b>对公打款认证</span>-->
        </div>
      </el-form-item>
    </el-form>
    <div class="secondAuthHeader">
      <div>当前认证组织： {{ pageInfo.enterpriseName }}</div>
      <p v-show="activeIndex === 0">根据当前组织机构信息自动生成一份授权书发送给法定代表人，法定代表人本人签署后可完成实名认证
        <el-button type="text" @click="viewPowerAttorney">查看授权书</el-button>
      </p>
      <ul v-show="activeIndex === 2">
        <li>请用您的企业对公账户打一笔认证款项，金额为0.01元，到账号后完成企业认证</li>
        <li>此处打款只作为认证使用，请勿随意打款，打款金额不做退还</li>
      </ul>
    </div>
    <div v-show="activeIndex === 0" style="margin-bottom: 20px">
      <p style="color: #666666;font-size: 12px">
        可通过以下两种方式发送给法定代表人进行签署，签署完成后企业认证自动通过，二维码/短信链接有效期7天</p>
      <div class="tabBox">
        <div :class="[{'tabActive': tabIndex === 1}]" @click="tabIndex = 1">
          <span>方式一：分享二维码/链接</span>
        </div>
        <div :class="[{'tabActive': tabIndex === 2}]" @click="tabIndex = 2">
          <span>方式二：直接发送短信</span>
        </div>
      </div>
      <div v-if="tabIndex === 1">
        <div class="flexcolumn flexcenter margin-top3">
          <div style="width: 180px;height: 180px;margin: 20px auto">
            <img :src="pageInfo.authenticationQrcode" alt="" style="width: 100%;height: 100%;">
          </div>
          <div style="padding-bottom: 50px">
            <el-button @click="copyLink(pageInfo.authenticationUrl)">复制链接</el-button>
            <el-button type="primary" @click="queryResult">查询认证结果</el-button>
          </div>
        </div>
      </div>
      <div v-if="tabIndex === 2">
        <el-form v-show="!isPostMessage" ref="postMessageModelElRef" :model="postMessageModel"
                 :rules="postMessageModelRules" style="width: 60%;margin: 80px auto 0">
          <el-form-item class="modelRight" label="法定代表人手机号" prop="phone">
            <el-input v-model="postMessageModel.phone" :maxlength="11" placeholder="法定代表人手机号" show-word-limit />
          </el-form-item>
          <el-form-item>
            <div class="flexcenter" style="margin-bottom: 50px">
              <el-button :loading="submitMessageLoading" type="primary" @click="submitMessage">确认发送</el-button>
            </div>
          </el-form-item>
        </el-form>
        <div v-show="isPostMessage" class="flexcolumn flexcenter" style="margin-top: 80px">
          <img alt="" src="https://asset.tsign.cn/apps/realname_v3/prod/2.0.2/img/money-wait.8d1ec0fd.png"
               style="width: 92px;height: 82px">
          <p style="margin: 20px 0">
            签署通知已发送给{{ pageInfo.legalPerson }}（{{ postMessageModel.phone }}），请等待法定代表人签署</p>
          <div style="margin-bottom: 50px">
            <el-button @click="isPostMessage = false">修改手机号</el-button>
            <el-button type="primary" @click="submitMessage">再次发送短信</el-button>
            <el-button type="primary" @click="queryResult">查询认证结果</el-button>
          </div>
        </div>
      </div>
    </div>
    <div v-show="activeIndex === 1" style="margin-bottom: 20px">
      <p style="color: #666666;font-size: 12px">
        法人本人授权可通过以下两种方式，完成授权后企业认证自动通过，二维码/短信链接有效期7天</p>
      <div class="tabBox">
        <div :class="[{'tabActive': tabPersonIndex === 1}]" @click="tabPersonIndex = 1">
          <span>方式一：手机认证</span>
        </div>
        <div :class="[{'tabActive': tabPersonIndex === 2}]" @click="tabPersonIndex = 2">
          <span>方式二：人脸识别</span>
        </div>
      </div>
      <div v-show="tabPersonIndex === 1">
        <el-form style="width: 60%;margin: 20px auto 0" :model="legalPersonTabFirstModel" ref="legalPersonTabFirstModelElRef" :rules="legalPersonTabFirstRules">
          <el-form-item class="modelRight" label="姓名" prop="legalPerson">
            <el-input v-model="legalPersonTabFirstModel.legalPerson" placeholder="在此输入姓名" show-word-limit />
          </el-form-item>
          <el-form-item class="modelRight" label="身份证号" prop="idcard">
            <el-input v-model="legalPersonTabFirstModel.idcard" :maxlength="18" placeholder="在此输入身份证号" show-word-limit />
          </el-form-item>
          <el-form-item class="modelRight" label="手机号" prop="phone">
            <el-input v-model="legalPersonTabFirstModel.phone" :maxlength="11" placeholder="在此输入手机号" show-word-limit>
              <template slot="append">
                <el-button type="text" style="margin: 0 5px" @click="getCodeNumber">{{codeNumber}}</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item class="modelRight" label="手机验证码" prop="phoneCode">
            <el-input v-model="legalPersonTabFirstModel.phoneCode" :maxlength="4" placeholder="在此输入手机验证码" show-word-limit />
          </el-form-item>
        </el-form>
      </div>
      <div v-show="tabPersonIndex === 2">
        <el-form v-show="!isQrCode" style="width: 60%;margin: 20px auto 0" :model="legalPersonTabSecondModel" ref="legalPersonTabSecondModelElRef" :rules="legalPersonTabSecondRules">
          <el-form-item class="modelRight" label="姓名" prop="legalPerson">
            <el-input v-model="legalPersonTabSecondModel.legalPerson" placeholder="在此输入姓名"/>
          </el-form-item>
          <el-form-item class="modelRight" label="身份证号" prop="idcard">
            <el-input v-model="legalPersonTabSecondModel.idcard" :maxlength="18" placeholder="在此输入身份证号" show-word-limit />
          </el-form-item>
        </el-form>
        <div v-show="isQrCode" class="flexcolumn flexcenter margin-top3">
          <div ref="isQrCodeRef"></div>
          <div class="margin-top4" style="margin-bottom: 20px">
            <el-button @click="legalPersonTabSecondModelReset">重新生成</el-button>
          </div>
        </div>
      </div>
    </div>
    <div v-show="activeIndex === 2">
      <el-form ref="secondModelElRef" :model="secondModel" :rules="secondModelRules" class="classModel" inline>
        <el-form-item class="modelLeft" label="上传授权书" prop="upload">
          <el-button style="float: right" type="text">查看授权书示例</el-button>
          <div style="margin-left: -90px;float:left;margin-top: 40px">
            <div>步骤一： 下载授权书，确认授权书内容</div>
            <el-button icon="" style="margin: 10px 0">下载授权书模板</el-button>
            <div>步骤二： 必须用下载的授权书模板打印后加盖实体公章上传</div>
            <el-upload
              :show-file-list="false"
              action="https://jsonplaceholder.typicode.com/posts/">
              <img v-if="imageUrl" :src="imageUrl" alt="" class="avatar" />
              <div v-else class="flexcenter flexcolumn" style="width: 120px;height: 120px;border: 1px solid #ededed;">
                <i class="el-icon-plus avatar-uploader-icon"></i>
                点击上传授权书
              </div>
            </el-upload>
            <span>仅支持jpg、jpeg、png、pdf格式，大小限制10M</span>
          </div>
        </el-form-item>
        <el-form-item class="modelRight" label="汇入的大鸿签对公账户" prop="price">
          <el-button style="float: right; margin-left: 210px;" type="text">查看打款细则</el-button>
          <div class="modelRightContent" style="">
            <ul style="margin-top: 10px">
              <li>
                <div>组织机构名称</div>
                <div>杭州天谷信息科技有限公司</div>
              </li>
              <li>
                <div>企业对公账户</div>
                <div>30206857000001</div>
              </li>
              <li>
                <div>开户银行支行名称</div>
                <div>平安银行杭州西湖支行</div>
              </li>
            </ul>
            <div class="margin-top3" style="font-weight: 600;">汇款金额：<span style="color: #e63740;font-size: 26px">￥0.01</span>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div v-show="activeIndex === 1" class="flexright" style="width: 98%;padding-bottom: 50px">
      <el-button @click="currentPrev" v-show="tabPersonIndex === 1">上一步</el-button>
      <el-button @click="currentPrev" v-show="tabPersonIndex === 2 && !isQrCode">上一步</el-button>
      <el-button v-show="tabPersonIndex === 1 || !isQrCode" type="primary" @click="confirmLegalPersonTabModel" :loading="confirmLegalPersonTabModelLoading">{{this.tabPersonIndex === 1 ? '提交认证':'生成二维码'}}</el-button>
    </div>
    <div v-show="activeIndex === 2" class="flexright" style="width: 98%;padding-bottom: 50px">
      <el-button @click="currentPrev">上一步</el-button>
      <el-button type="primary" @click="currentNext">确认</el-button>
    </div>
    <el-dialog :visible.sync="powerAttorneyVisible" center title="授权书" width="50%" @close="closePowerAttorneyDialog">
      <template slot="footer"></template>
      <div style="max-height: 65vh;overflow-y: auto;width: 100%">
        <img :src="pageInfo.authFile" alt="" style="width: 100%;height: auto">
      </div>
    </el-dialog>
  </div>
</template>

<script>
import QRCode from 'qrcodejs2';

import {
  getAuthenticationLink,
  getEnterpriseInformationAuthentication,
  postSmsPhoneCode,
  postPhoneAuthenticationInfo,
} from "@/api/company";
import Cookies from "js-cookie";

const secondModelRef = {
  upload: "",
  price: ""
};

const postMessageModelRef = {
  phone: ""
};

const legalPersonTabFirstModelRef = {
  legalPerson: '',
  idcard: '',
  phone: '',
  phoneCode: ''
}
const legalPersonTabSecondModelRef = {
  legalPerson: '',
  idcard: ''
}

export default {
  name: "secondAuth",
  props: {
    pageInfo: {
      type: Object,
      require: true
    }
  },
  data() {
    return {
      activeIndex: 0,
      tabIndex: 1,
      postMessageModel: Object.assign({}, postMessageModelRef),
      secondModel: Object.assign({}, secondModelRef),
      secondModelRules: {
        upload: [{ required: true, message: "请上传授权书", trigger: "blur" }],
        price: [{ required: true, message: "请完善汇入的大鸿签对公账户", trigger: "blur" }]
      },
      postMessageModelRules: {
        phone: [
          { required: true, message: "请填写法定代表人手机号", trigger: "blur" },
          { pattern: /^1\d{10}$/, message: "请输入正确的手机号", trigger: "blur" }
        ]
      },
      imageUrl: "",
      powerAttorneyVisible: false,
      submitMessageLoading: false,
      isPostMessage: false,
      tabPersonIndex: 1,
      legalPersonTabFirstModel: Object.assign({}, legalPersonTabFirstModelRef),
      legalPersonTabSecondModel: Object.assign({}, legalPersonTabSecondModelRef),
      legalPersonTabFirstRules: {
        legalPerson: [
          { required: true, message: "请填写姓名", trigger: "blur" }
        ],
        idcard: [
          { required: true, message: "请填写身份证号", trigger: "blur" },
          { pattern: /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/,
            message: "请输入正确的身份证号",
            trigger: "blur"
          }
        ],
        phone: [
          { required: true, message: "请填写手机号", trigger: "blur" },
          { pattern: /^1\d{10}$/, message: "请填写正确的手机号", trigger: "blur" }
        ],
        phoneCode: [{ required: true, message: "请填写验证码", trigger: "blur" }]
      },
      legalPersonTabSecondRules: {
        legalPerson: [
          { required: true, message: "请填写姓名", trigger: "blur" }
        ],
        idcard: [
          { required: true, message: "请填写身份证号", trigger: "blur" },
          { pattern: /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/,
            message: "请输入正确的身份证号",
            trigger: "blur"
          }
        ],
      },
      codeNumber: '获取验证码',
      confirmLegalPersonTabModelLoading: false,
      isQrCode: false
    };
  },
  mounted() {},
  methods: {
    currentPrev() {
      this.$forceUpdate()
      this.$emit("goIndex", 1);
    },
    currentNext() {
      this.$emit("goIndex", 3);
    },
    copyLink(link) {
      this.$copyText(link).then(() => {
        this.$message.success("复制成功");
      }, err => {
        console.log(err);
      });
    },
    queryResult() {
      console.log("查询", this.pageInfo.enterpriseName, "的认证结果");
      getEnterpriseInformationAuthentication({
        enterpriseName: this.pageInfo.enterpriseName,
        userId: Cookies.get("admin_id")
      }).then(res => {
        if (res.code === 200) {
          if (res.result.state === 1) {
            this.$message.info("等待法人授权中，请稍后");
          } else {
            this.$message.success("法人签署授权完成，企业创建成功");
          }
        }
      });
    },
    submitMessage() {
      this.$refs.postMessageModelElRef.validate(bool => {
        if (bool) {
          console.log("给", this.postMessageModel.phone, "发送短信");
          this.submitMessageLoading = true;
          getAuthenticationLink({ phone: this.postMessageModel.phone, enterpriseId: this.pageInfo.id }).then(res => {
            this.submitMessageLoading = false;
            if (res.code === 200) {
              this.isPostMessage = true;
              this.$message.success(res.message);
            }
          }).catch(() => {
            this.$message.error("请检查手机号或网络不通畅");
          });
        }
      });
    },
    viewPowerAttorney() {
      this.powerAttorneyVisible = true;
    },
    closePowerAttorneyDialog() {
      this.powerAttorneyVisible = false;
    },
    getCodeNumber(){
        if(this.legalPersonTabFirstModel.phone && this.codeNumber === '重新发送' || this.codeNumber === '获取验证码') {
          postSmsPhoneCode({phone: this.legalPersonTabFirstModel.phone}).then(res=>{
            if(res.code === 200){
              this.$message.success(res.message)
            }
          })
          let seconds = 60
          this.codeNumber = seconds + 's后重新发送'
          let interval = setInterval(() => {
            this.codeNumber = seconds -= 1
            this.codeNumber += 's后重新发送'
            if (seconds <= 0) {
              clearInterval(interval)
              this.codeNumber = '重新发送'
            }
          }, 1000)
        }
    },
    confirmLegalPersonTabModel(){
      if(this.tabPersonIndex === 1){
        this.$refs.legalPersonTabFirstModelElRef.validate(bool=>{
          if(bool){
            this.confirmLegalPersonTabModelLoading = true
            let data = {
              ...this.legalPersonTabFirstModel,
              enterpriseId: this.pageInfo.id
            }
            postPhoneAuthenticationInfo(data).then(res=>{
              this.confirmLegalPersonTabModelLoading = false
              if(res.code === 200){
                this.confirmLegalPersonTabModelLoading = false
                this.$message({
                  type: 'success',
                  message: res.message,
                  duration: 2000
                })
                setTimeout(()=>{
                  this.$router.replace({
                    path: '/business/allCompany'
                  })
                },2000)
              }
            }).catch(err=>{
              this.confirmLegalPersonTabModelLoading = false
            })
          }
        })
      }else if(this.tabPersonIndex === 2){
        this.$refs.legalPersonTabSecondModelElRef.validate(bool=>{
          if(bool){
            this.bindQRCode()
            this.isQrCode = true
          }
        })
      }
    },
    bindQRCode: function () {
      // let path = `https://www.signzg.com/pcface/index.html?enterpriseId=${this.pageInfo.id}&idcard=${this.legalPersonTabSecondModel.idcard}&legalPerson=${encodeURIComponent(this.legalPersonTabSecondModel.legalPerson)}&type=1#/`
      let path = `http://192.168.10.129:8081/?enterpriseId=${this.pageInfo.id}&idcard=${this.legalPersonTabSecondModel.idcard}&legalPerson=${encodeURIComponent(this.legalPersonTabSecondModel.legalPerson)}&type=1`
      console.log(path);
      this.$refs.isQrCodeRef.innerHTML = ""//词句代码将之前的二维码清空了
      new QRCode(this.$refs.isQrCodeRef, {
        text: path,
        width: 200,
        height: 200,
        colorDark: "#333333", //二维码颜色
        colorLight: "#ffffff", //二维码背景色
        correctLevel: QRCode.CorrectLevel.L//容错率，L/M/H
      })
      this.$refs.isQrCodeRef.title = ''
    },
    legalPersonTabSecondModelReset(){
      this.isQrCode = false
      this.$refs.legalPersonTabSecondModelElRef.resetFields()
    }
  }
};
</script>

<style lang="scss" scoped>
.secondAuth {
  padding: 0 40px;

  .secondAuthHeader {
    font-size: 14px;

    > div:first-child {
      font-weight: 600;
      margin-bottom: 10px;
    }

    > ul {
      margin-bottom: 10px;
      padding-left: 20px;
    }

    > ul > li {
      list-style: disc;
      color: #666666;
      margin-bottom: 10px;

      &:last-child {
        margin-bottom: 30px;
      }
    }
  }

  .secondAuthRadio {
    .btnList {
      margin-top: 40px;
      display: flex;
      align-items: center;

      > span {
        width: 321px;
        height: 60px;
        border: 1px solid #e5e6eb;
        display: flex;
        align-items: center;
        justify-items: center;
        padding: 17px 24px;
        box-sizing: border-box;
        margin-left: 18px;
        cursor: pointer;
        font-weight: 600;
        font-size: 16px;
        border-radius: 5px;

        b {
          font-size: 22px;
          margin-right: 5px;
        }
      }

      .btnListActive {
        color: #333 !important;
        border-color: #e63740 !important;
        background-color: #fef9f9 !important;
      }
    }
  }

  .tabBox {
    display: flex;
    align-items: center;
    justify-items: center;
    height: 60px;
    border: 1px dashed #e0e0e0;
    margin-top: 15px;
    box-sizing: border-box;

    > div {
      width: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      border-right: 1px dashed #e0e0e0;
      height: 100%;
      box-sizing: border-box;

      > span {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        border-bottom: 4px solid;
        border-color: rgba(255, 255, 255, 0);
      }
    }

    .tabActive {
      background-color: #fafbfd;

      > span {
        border-color: #e63740 !important;
      }
    }
  }

  .classModel {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

    .modelLeft,
    .modelRight {
      width: 48%;
      border: 1px dashed rgb(201, 205, 212);;
      padding: 10px 20px 20px;
      background-color: #fafbfd;
      box-sizing: border-box;
      height: 365px;
      overflow: hidden;

      :deep(.el-form-item__label) {
        font-weight: 600;
      }
    }

    .modelRight {
      .modelRightContent {
        float: left;
        margin-top: 40px;
        margin-left: -160px;
        height: 300px;
        overflow: hidden;

        > ul > li {
          line-height: 24px;
          margin: 16px 0;
        }

        > div {
          margin: 20px 0 130px;
        }
      }
    }
  }
}
</style>